package br.com.avaliacao;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;

import android.app.Activity;
import android.net.http.AndroidHttpClient;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;

public class AvaliacaoCredito extends Activity implements Runnable
{

	private HttpResponse response;
	private Handler handler = new Handler();
	private AvaliacaoParser avaliacaoParser;

	public AvaliacaoCredito()
	{
		avaliacaoParser = new AvaliacaoParser(this);
	}

	private Runnable threadUpdate = new Runnable()
	{
		public void run()
		{
			try
			{
				avaliacaoParser.lerMensagem(response);
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.analise);

		configureButtons();
	}

	private void configureButtons()
	{
		configureButtonAvaliar();
		configureButtonLimpar();
	}

	private void configureButtonLimpar()
	{
		Button buttonLimpar = (Button) findViewById(R.id.Button02);
		buttonLimpar.setOnClickListener(new View.OnClickListener()
		{
			public void onClick(View v)
			{
				limpar((TableLayout) findViewById(R.id.TableLayout));
			}
		});
	}

	private void limpar(TableLayout tableLayout)
	{
		for (int i = 0; i < tableLayout.getChildCount(); i++)
		{
			View childComponent = tableLayout.getChildAt(i);
			if (childComponent instanceof TableRow)
			{
				TableRow tableRow = (TableRow) childComponent;
				View editTextComponent = tableRow.getChildAt(0);
				if (editTextComponent instanceof EditText)
				{
					((EditText) editTextComponent).setText("");
				}
			}
		}

	}

	private void configureButtonAvaliar()
	{
		Button buttonAvaliar = (Button) findViewById(R.id.Button01);
		buttonAvaliar.setOnClickListener(new View.OnClickListener()
		{
			public void onClick(View v)
			{
				new Thread(AvaliacaoCredito.this).start();
			}
		});
	}

	public void run()
	{
		try
		{
			EditText textCPF = (EditText) findViewById(R.id.EditTextCPF);
			String urlServico = "http://169.254.53.76:8040/services/AvaliacaoServico/avaliar/cpf/" + textCPF.getText();
			HttpGet httpGet = new HttpGet(urlServico);

			AndroidHttpClient httpClient = AndroidHttpClient.newInstance("");
			response = httpClient.execute(httpGet);

			handler.post(threadUpdate);
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}
}